package com.tpe.model.cloud;

import java.util.List;

import com.amazonaws.auth.ClasspathPropertiesFileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.AmazonSQSClient;
import com.amazonaws.services.sqs.model.DeleteMessageRequest;
import com.amazonaws.services.sqs.model.Message;
import com.amazonaws.services.sqs.model.ReceiveMessageRequest;
import com.amazonaws.services.sqs.model.SendMessageRequest;

public class QueueUtil {

	private static AmazonSQS sqs;

	private QueueUtil() {
	}

	public static void sendMessage(String msg, String queue) {
		try {
			getSqs().sendMessage(
					new SendMessageRequest().withQueueUrl(queue)
							.withMessageBody(msg));

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static List<Message> retrieveMessages(String url) {
		return getSqs().receiveMessage(
				new ReceiveMessageRequest().withQueueUrl(url)).getMessages();
	}

	public static void deleteQueueItem(Message msg, String queueUrl) {
		String messageReceiptHandle = msg.getReceiptHandle();
		getSqs().deleteMessage(
				new DeleteMessageRequest().withQueueUrl(queueUrl)
						.withReceiptHandle(messageReceiptHandle));
	}

	private static AmazonSQS getSqs() {
		if (sqs == null) {
			sqs = new AmazonSQSClient(
					new ClasspathPropertiesFileCredentialsProvider());
			sqs.setRegion(Region.getRegion(Regions.US_WEST_2));
		}
		return sqs;
	}
}